import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Message } from 'element-ui'
import { asyncRoutes } from '@/router/index'
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      Message({ message: '您已登录', type: 'warning' })
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        console.log(roles)
        const filterlist = asyncRoutes.filter(item =>
          roles.menus.includes(item.children[0].name)
        )
        filterlist.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterlist)
        console.log(filterlist)
        store.commit('user/setroutes', filterlist)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
